package com.sean.bigdata.chapter03;

import java.util.Scanner;
import java.util.Stack;

/**
 * 后缀操作
 */
public class EndOperation {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String exp, again;
        do {
            System.out.println("输入表达式");
            exp = in.nextLine();
            PostfixEvaluator postfixEvaluator = new PostfixEvaluator();
            Integer result = postfixEvaluator.evalute(exp);
            System.out.println("result" + result);
            System.out.println("输入Y代表继续");
            again = in.nextLine();
        } while (again.equalsIgnoreCase("y"));
    }
}

class PostfixEvaluator {


    private Stack<Integer> stack;

    public PostfixEvaluator() {
        stack = new Stack<>();
    }

    public int evalute(String exp) {
        Scanner scanner = new Scanner(exp);
        int c = 0;
        while (scanner.hasNext()) {
            String oper = scanner.next();
            if (isOper(oper)) {
                int a = stack.pop();
                int b = stack.pop();
                c = evalute(b, a, oper);
                stack.push(c);
            } else {
                stack.push(Integer.valueOf(oper));
            }
        }
        return c;
    }

    private boolean isOper(String oper) {
        return oper.equals("+") ||
                oper.equals("-") ||
                oper.equals("*") ||
                oper.equals("/");
    }

    private int evalute(int a, int b, String oper) {
        switch (oper) {
            case "+":
                return a + b;
            case "-":
                return a - b;
            case "*":
                return a * b;
            case "/":
                return a / b;
        }
        return 0;
    }

}
